##client.py
from socket import *
import simplejson as json
import logging
import stomp

HOST = 'devmonsvr01'
PORT = 29876
ADDR = (HOST,PORT)
BUFSIZE = 4096

PIDFILE = ''


def main():

    cli = socket( AF_INET,SOCK_STREAM)
    cli.connect((ADDR))
    logging.info('Connecting to %s port %s' % (ADDR))

    # Write pid file if not already running
    if os.path.isfile(PIDFILE):
        pid = open(PIDFILE).read()
        try:
            os.kill(int(pid), 0)
            logging.error('Process with pid %s already exists, exiting', pid)
            sys.exit(1)
        except OSError:
            pass
    file(PIDFILE, 'w').write(str(os.getpid()))

    # Connect to message broker
    logging.info('Connect to broker')
    try:
        conn = stomp.Connection(
                   BROKER_LIST,
                   reconnect_sleep_increase = 5.0,
                   reconnect_sleep_max = 120.0,
                   reconnect_attempts_max = 20
               )
        conn.set_listener('', MessageHandler())
        conn.start()
        conn.connect(wait=True)

    except Exception, e:
        logging.error('Stomp connection error: %s', e)
        sys.exit(1)

    while True:
        data = cli.recv(BUFSIZE)
        print data
        logging.info('Recieve data: %s' % data)

if __name__ == '__main__':
      main()
